<?php

/**
 * 品牌模型
 * File Name：BrandModel.php
 * File Encoding：UTF-8
 * File New Time：2014-5-20 14:08:31
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class BrandModel extends BaseModel {

    public function tableName() {
        return '{{brand}}';
    }

    public function rules() {
        return array(
            array('brand_name', 'required', 'message' => '品牌名称不能为空！'),
            array('brand_name_en', 'required', 'message' => '英文名称不能为空！'),
            array('initial', 'required', 'message' => '英文首字母不能为空！'),
            array('logo,brand_des,disabled,is_new,is_hot,is_best,listorder,brand_poster', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 添加品牌
     * @param type $data
     * @return boolean
     */
    public function add($data = array()) {
        if (empty($data)) {
            $data = $_POST;
        }
        $this->attributes = $data;
        //新增
        $this->setIsNewRecord(true);
        //验证并添加
        if ($this->validate() && $this->save()) {
            return true;
        }
        return false;
    }

    /**
     * 修改品牌
     * @param type $data
     */
    public function edit($data = array()) {
        if (empty($data)) {
            $data = $_POST;
        }
        $model = $this->findByPk($data['brand_id']);
        if (empty($model)) {
            $this->addError('', '该信息不存在！');
            return false;
        }
        if (!isset($data['is_best'])) {
            $data['is_best'] = 0;
        }
        if (!isset($data['is_new'])) {
            $data['is_new'] = 0;
        }
        if (!isset($data['is_hot'])) {
            $data['is_hot'] = 0;
        }
        $model->attributes = $data;
        //验证并添加
        if ($model->validate() && $model->save()) {
            return true;
        }
        $this->addErrors($model->getErrors());
        return false;
    }

    /**
     * 获取Brand数组
     * @return array
     */
    public function getBrandArray($isCache = true) {
        //缓存key
        $key = "BrandModel_getBrandArray";
        if (!$isCache) {
            Yii::app()->cache->delete($key);
        }
        //读取缓存
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $cache = array();
            $data = $this->findAll($this->where(array('order' => 'listorder DESC,brand_id ASC')));
            if (!empty($data)) {
                foreach ($data as $rs) {
                    $cache[$rs->brand_id] = $rs->brand_name;
                }
            }
            //默认缓存3600秒
            Yii::app()->cache->set($key, $cache, 3600);
        }
        return $cache;
    }

    protected function afterSave() {
        $this->getBrandArray(false);
    }

}
